package com.system.controller;

import com.alibaba.fastjson.JSONObject;
import com.system.pojo.Item;
import com.system.service.ItemService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;

import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletRequest;
import java.util.List;

@Controller
public class ItemController {
    @Autowired
    private ItemService itemService;

    @RequestMapping("selectItemForPage")
    @ResponseBody
    public String selectItemForPage(Item item, @RequestParam(defaultValue="1")int page, @RequestParam(defaultValue="5")int limit){
        List<Item> list = itemService.selectItem(item);
        List<Item> people = itemService.selectItemByPage(item,page, limit);
        JSONObject jsonObject = new JSONObject();
        jsonObject.put("code", 0);
        jsonObject.put("count",list.size());
        jsonObject.put("data", people);
        jsonObject.put("msg", "查询成功");
        return jsonObject.toJSONString();
    }

    @RequestMapping("delBuyer")
    @ResponseBody
    public String delBuyer(Item item){
        JSONObject jsonObject = new JSONObject();
        String id = item.getItemId().toString();
        try {
            itemService.delItem(id);
            jsonObject.put("code", 0);
            jsonObject.put("msg", "删除成功");
        }catch (Exception e){
            e.printStackTrace();
            jsonObject.put("code", 1);
            jsonObject.put("msg", "删除失败");
        }
        return jsonObject.toJSONString();
    }

    @RequestMapping("insertItem")
    @ResponseBody
    public String insertItem(Item item, HttpServletRequest request){
        Cookie[] cookies = request.getCookies();
        JSONObject jsonObject = new JSONObject();
        if (cookies!=null){
            System.out.println(cookies);
        }
        try {
            itemService.insertItem(item);
            jsonObject.put("code", 0);
            jsonObject.put("msg", "查询成功");
        }catch (Exception e){
            e.printStackTrace();
            jsonObject.put("code", 1);
            jsonObject.put("msg", "删除失败");
        }
        return jsonObject.toJSONString();
    }

    @RequestMapping("updateItem")
    @ResponseBody
    public String selectItemForItemId(Item item){
        JSONObject jsonObject = new JSONObject();
        try {
            itemService.updateItem(item);
            jsonObject.put("code", 0);
            jsonObject.put("msg", "修改成功");
        }catch (Exception e){
            e.printStackTrace();
            jsonObject.put("code", 1);
            jsonObject.put("msg", "修改失败");
        }
        return jsonObject.toJSONString();
    }

}
